<template>
    <div class="user-config">
        <div class="page-header">
            <h2>用户配置</h2>
            <div>
                <el-button type="primary" @click="openAddDialog">添加用户</el-button>
                <el-button class="refreshUserData" :icon="Refresh" @click="refreshUsers" circle />
            </div>
        </div>

        <!-- 用户列表 -->
        <el-table :data="users" style="width: 100%" border>
            <el-table-column label="用户名" prop="userName"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="备注" prop="remark"></el-table-column>
            <el-table-column label="部门">
                <template #default="{ row }">
                    <el-tag v-for="(item, index) in row.departmentNames" :key="index" :type="'success'" :size="'medium'"
                        effect="plain" class="role-tag">
                        {{ item }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="角色">
                <template #default="{ row }">
                    <el-tag v-for="(item, index) in row.roleNames" :key="index" :type="'success'" :size="'medium'"
                        class="role-tag">
                        {{ item }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="启用状态">
                <template #default="{ row }">
                    <el-tag :type="row.enable ? 'success' : 'danger'">
                        {{ row.enable ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime"></el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button @click="openEditDialog(row)" type="text" size="small">编辑</el-button>
                    <el-button @click="deleteUser(row.id)" type="text" size="small" style="color: red;">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加/编辑用户弹窗 -->
        <el-dialog v-model="dialogVisible" title="用户配置" width="400px" :before-close="closeDialog">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="dialog-form">
                <el-form-item v-if="!isEdit" label="登录名" prop="loginName">
                    <el-input v-model="form.loginName" placeholder="请输入登录名" />
                </el-form-item>
                <el-form-item label="用户昵称">
                    <el-input v-model="form.userName" placeholder="请输入用户昵称" />
                </el-form-item>
                <el-form-item label="密码" prop="pwd">
                    <el-input v-model="form.pwd" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="form.role" multiple placeholder="请选择用户角色">
                        <el-option v-for="option in roleOptions" :key="option.id" :label="option.name"
                            :value="option.id" />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="!isEdit" label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
                <el-form-item label="启用状态">
                    <el-switch v-model="form.enable" active-text="启用" inactive-text="禁用" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog" size="medium">取消</el-button>
                <el-button type="primary" @click="saveUser" size="medium">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { onMounted, inject, ref, reactive } from 'vue';
const axios = inject('$axios'); // 从全局属性注入
import { Refresh } from '@element-plus/icons-vue'

const dialogVisible = ref(false);
const form = ref({
    id: 0,
    loginName: '',
    createTime: '',
    updateTime: '',
    enable: true,
    email: '',
    remark: '',
    role: ''
});
const isEdit = ref(false)
const roleOptions = ref()
const users = ref([]);
const formRef = ref(null);

const rules = ref({
    loginName: [
        { required: true, message: '登录名不能为空', trigger: 'blur' }
    ],
    role: [
        { required: true, message: '角色不能为空', trigger: 'blur' }
    ],
    pwd: [
        { required: true, message: '密码不能为空', trigger: 'blur' }
    ]
});

const openAddDialog = () => {
    form.value = {
        id: 0,
        userName: '',
        createTime: '',
        updateTime: '',
        enable: true,
        email: '',
        remark: '',
        pwd: '',
        loginName: ''
    };
    isEdit.value = false;
    dialogVisible.value = true;
};

const openEditDialog = (row) => {
    rules.value.loginName[0].required = false;
    rules.value.pwd[0].required = false;
    rules.value.role[0].required = false;
    form.value = { ...row };
    form.value.role = roleOptions.value.filter(option => row.roleNames.includes(option.name)).map(option => option.id);
    dialogVisible.value = true;
    isEdit.value = true;
};

const closeDialog = () => {
    if (formRef.value) {
        formRef.value.resetFields();
    }
    rules.value.loginName[0].required = true;
    rules.value.pwd[0].required = true;
    rules.value.role[0].required = true;
    dialogVisible.value = false;
};

const saveUser = async () => {
    const valid = await new Promise((resolve, reject) => {
        formRef.value.validate((valid) => {
            if (!valid) {
                ElMessage.error('请完善必填项');
                return (new Error('请完善必填项'));
            } else {
                resolve(valid);
            }
        })
    });

    var dataParam = {
        'Id': form.value.id ?? 0,
        'LoginName': form.value.loginName,
        'Roles': form.value.role,
        'Enable': form.value.enable,
        'Remark': form.value.remark,
        'Pwd': form.value.pwd,
        'UserName': form.value.userName
    };

    let result;

    if (dataParam.Id > 0) {
        result = await axios.post('/User/UpdataUserAsync', dataParam);
    } else {
        result = await axios.post('/User/AddUserAsync', dataParam);
    }

    if (result.statusCode == 200 && result.success == true) {
        ElMessage.success(result.message);
        getUsers();
    } else {
        ElMessage.error(result.message);
    }

    closeDialog();
};

const deleteUser = async (id) => {
    const result = await axios.get('/User/DeleteUserByIdAsync?id=' + id);
    if (result.statusCode == 200 && result.success == true) {
        ElMessage.success('用户删除成功');
        await getUsers();
    } else {
        ElMessage.error(result.message);
    }
};

const getUsers = async () => {
    const result = await axios.get('/User/QueryUsersAsync');
    if (result.statusCode == 200 && result.success == true) {
        users.value = result.response;
    } else {
        ElMessage.error('获取用户列表失败');
    }
};

const getRoles = async () => {
    const result = await axios.get('/Role/QueryRoleAsync');
    if (result.statusCode == 200 && result.success == true) {
        roleOptions.value = result.response;
    } else {
        ElMessage.error('获取角色列表失败');
    }
}

const refreshUsers = () => {
    getUsers();
    ElMessage.success('刷新成功');
}

onMounted(async () => {
    await getUsers();
    setTimeout(() => getRoles(), 100);
});
</script>

<style scoped>
.role-tag {
    margin-top: 1px;
    margin-right: 8px;
    font-size: 14px;
    border-radius: 4px;
    /* 让标签有圆角，增加现代感 */
    padding: 4px 8px;
    /* 给标签添加一些内边距，提升可读性 */
}

.user-config {
    border-radius: 8px;
    height: 100%;
}

.page-header {
    display: flex;
    justify-content: space-between;
    font-weight: bold;
}

.refreshUserData {
    margin-left: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding: 10px 20px;
}

.dialog-footer .el-button {
    width: 90px;
    margin-left: 15px;
}

.el-button--primary {
    background-color: #409eff;
    border-color: #409eff;
}

.el-button--primary:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
}
</style>
